package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.helpers.AskNumAmtHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlReadMode;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.css.parser.property.PrimitivePropertyBuilders;

import java.io.File;
import java.sql.Connection;
import java.util.*;

@Component("CMB01BatPayRec")
public class CMB01BatPayRec extends CMB01Base implements IBatPayRec {
    private static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    private static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=?;";

    /**
     * 批量代付指令提交
     * @param p_req1988 批量代付请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        if ("198802".equals(p_req1988.reqHeader.commandCode) || "198801".equals(p_req1988.reqHeader.commandCode)) {
            return d_BatPayRec(p_req1988);      //代发工资
        } else if ("198803".equals(p_req1988.reqHeader.commandCode)){
            return d_BatPayRec_New(p_req1988);  //代发
        } else {
            return null;
        }
    }

    /**
     * 批量代扣指令提交
     * @param p_req9188 批量代扣请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    //批量代收和批量代付提交
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        AskNumAmtHelper askAmtHelper = null;
        try {
            //N03010:代发工资   N03020:代发   N03030:代扣
            //198802 代发工资
            String tmpBUSCOD = "";
            if ("1988".equals(p_reqBat.reqHeader.transType)) {
                if (p_reqBat.reqHeader.commandCode.equals("198802")) {
                    tmpBUSCOD = "N03010";
                } else {
                    tmpBUSCOD = "N03020";
                }
            } else if ("9188".equals(p_reqBat.reqHeader.transType)) {
                tmpBUSCOD = "N03030";
            }

            String tmpBUSMOD = getBankConfig().getMapValueByKey("busmod" + tmpBUSCOD, p_reqBat.useType);
            String tmpC_TRSTYP = getBankConfig().getMapValueByKey("ctrstyp" + tmpBUSCOD, p_reqBat.useType);
            String tmp_TRSTYP = getBankConfig().getMapValueByKey("trstyp" + tmpBUSCOD, p_reqBat.useType);
            boolean isChecked = true;
            String tmpCheckMsg = "";
            if (StringHelper.isNullOrEmpty(tmpBUSMOD)) {
                isChecked = false;
                tmpCheckMsg = "未取到" + tmpBUSCOD + "的业务模式设置";
            }
            if (StringHelper.isNullOrEmpty(tmpBUSMOD)) {
                isChecked = false;
                if (tmpCheckMsg.length() > 0) {
                    tmpCheckMsg = tmpCheckMsg + "；";
                }
                tmpCheckMsg = tmpCheckMsg + "未取到" + tmpBUSCOD + "的交易代码名称设置";
            }
            if (!isChecked) {
                retAts.respCode = "0";
                retAts.respInfo = tmpCheckMsg;
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = "E9981";
                retAts.writeRetToATS();
                return retAts;
            }


            CMB01Header tmpBnkHeader = new CMB01Header();
            if ("918802".equals(p_reqBat.reqHeader.commandCode)) {
                tmpBnkHeader.FUNNAM = "NTAGCACL";
            } else {
                tmpBnkHeader.FUNNAM = "AgentRequest";
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, tmpBnkHeader);

            boolean isCompletePack = true;
            StringBuilder sbLogChk = new StringBuilder();
            if ("918802".equals(p_reqBat.reqHeader.commandCode)) {
                xmlWriter.writeStartElement("NTBUSMODY");
                xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);//业务模式
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("NTAGCAGCX1");
                xmlWriter.writeElementString("BEGTAG", "Y");//批次开始标志
                xmlWriter.writeElementString("ENDTAG", "Y");//批次结束标志
                xmlWriter.writeElementString("TTLAMT", p_reqBat.totalAmt);//总金额
                xmlWriter.writeElementString("TTLCNT", p_reqBat.totalNum);//总笔数
                xmlWriter.writeElementString("TTLNUM", "1");//总次数
                xmlWriter.writeElementString("CURAMT", p_reqBat.totalAmt);//本次金额
                xmlWriter.writeElementString("CURCNT", p_reqBat.totalNum);//本次笔数
                xmlWriter.writeElementString("CCYNBR", this.convertCurToBank(p_reqBat.ownCur));//交易货币
                xmlWriter.writeElementString("BBKNBR", p_reqBat.ownArea);//分行号
                xmlWriter.writeElementString("ACCNBR", p_reqBat.ownAct);//账号
                xmlWriter.writeElementString("CCYMKT", "0");//货币市场
                xmlWriter.writeElementString("TRSTYP", tmp_TRSTYP);//交易类型
                xmlWriter.writeElementString("NUSAGE", getBankConfig().getMapValueByKey("nusage", "*"));//用途
                xmlWriter.writeElementString("YURREF", p_reqBat.reqBatchNO);//对方参考号(取的是批次号)
                xmlWriter.writeEndElement();

                while (p_reqBat.readRecord()) {
                    XElement tmpXElement = new XElement("NTAGCDTLY1", "");
                    ReqPayRecDetail p_atsDetail = p_reqBat.readedDetail;
                    tmpXElement.addChild(new XElement("TRXSEQ", p_atsDetail.askNumber));//交易序号(取的是支付流水号)
//					tmpXElement.addChild(new XElement("TRXSEQ", "00000001"));
                    tmpXElement.addChild(new XElement("ACCNBR", p_atsDetail.payAct));//帐号
                    tmpXElement.addChild(new XElement("ACCNAM", p_atsDetail.payName));//户名
                    tmpXElement.addChild(new XElement("TRSAMT", p_atsDetail.payAmount));//金额
                    if (p_atsDetail.sameBnk != null && p_atsDetail.sameBnk.equals("1")) {
                        tmpXElement.addChild(new XElement("BNKFLG", "Y"));//系统内标志
                    } else {
                        tmpXElement.addChild(new XElement("BNKFLG", "N"));
                    }
                    nodeAnalysis(p_atsDetail.srcXElement, tmpXElement, getCharset());
                    xmlWriter.writeXElement(tmpXElement);
                }
                xmlWriter.writeEndDocument();//写入报文完成
            } else {
                xmlWriter.writeStartElement("SDKATSRQX");
                xmlWriter.writeElementString("BUSCOD", tmpBUSCOD);
                xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);
                xmlWriter.writeElementClosed("MODALS");
                xmlWriter.writeElementString("C_TRSTYP", tmpC_TRSTYP);
                xmlWriter.writeElementString("TRSTYP", tmp_TRSTYP);
                xmlWriter.writeElementClosed("EPTDAT");
                xmlWriter.writeElementString("DBTACC", p_reqBat.ownAct);
                xmlWriter.writeElementString("BBKNBR", p_reqBat.ownArea);
                xmlWriter.writeElementClosed("BANKAREA");
                xmlWriter.writeElementString("SUM", p_reqBat.totalAmt);
                xmlWriter.writeElementString("TOTAL", p_reqBat.totalNum);
                xmlWriter.writeElementString("CCYNBR", this.convertCurToBank(p_reqBat.ownCur));
                xmlWriter.writeElementClosed("CURRENCY");
                xmlWriter.writeElementString("YURREF", p_reqBat.reqBatchNO);
                //MEMO	用途	Z(1,42)
                //xmlWriter.writeElementString("MEMO", p_reqBat.useType);
                String bkMEMO = StringHelper.joinNotEmpty("-", p_reqBat.abstractATS, p_reqBat.useType);
                bkMEMO = StringHelper.subStringByByte(bkMEMO, getCharset(), 42);
                xmlWriter.writeElementString("MEMO", bkMEMO);
                xmlWriter.writeEndElement();
                try {
                    String userPartnerAccount = getBankConfig().getValueAsString("isUserPartnerAccount");
                    boolean isUserPartnerAccount = getBankConfig().getValueAsBool("isUserPartnerAccount");
                    boolean noAsk = false;//流水号不能在查询带回，需要存

                    if ("9188".equals(p_reqBat.reqHeader.transType)) {
                        if (StringHelper.hasAnyChar(userPartnerAccount)) {
                            noAsk = true;
                            askAmtHelper = new AskNumAmtHelper(p_reqBat.reqHeader.tenant, p_reqBat.getPayDateTime());
                        }
                    }
                    int rdCounting = 0;
                    //需要进行对账码拼接以及节点解析，采用XElement进行处理
                    while (p_reqBat.readRecord()) {
                        XElement tmpXElement = new XElement("SDKATDRQX", "");
                        if (p_reqBat.reqHeader.transType.equals("1988")) {
                            tmpXElement.addChild(new XElement("ACCNBR", p_reqBat.readedDetail.recAct));
                            tmpXElement.addChild(new XElement("CLTNAM", p_reqBat.readedDetail.recName));
                        } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                            tmpXElement.addChild(new XElement("ACCNBR", p_reqBat.readedDetail.payAct));
                            tmpXElement.addChild(new XElement("CLTNAM", p_reqBat.readedDetail.payName));
                        }
                        tmpXElement.addChild(new XElement("TRSAMT", p_reqBat.readedDetail.payAmount));
                        if (p_reqBat.readedDetail.sameBnk.equals("1")) {
                            tmpXElement.addChild(new XElement("BNKFLG", "Y"));
                            tmpXElement.addChild(new XElement("EACBNK", ""));
                            tmpXElement.addChild(new XElement("EACCTY", ""));
                        } else {
                            tmpXElement.addChild(new XElement("BNKFLG", "N"));
                            tmpXElement.addChild(new XElement("EACBNK", p_reqBat.readedDetail.getOppBankLocation()));
                            tmpXElement.addChild(new XElement("EACCTY", p_reqBat.readedDetail.getOppStandardArea()));
                        }

                        String trsDSP = "";
                        if (noAsk) {//流水号不能在查询带回，需要存数据库
                            rdCounting++;
                            askAmtHelper.saveToLoaclDb(p_reqBat, p_reqBat.readedDetail, rdCounting);
                            if (isUserPartnerAccount) {
                                trsDSP = getBankConfig().getMapValueByKey("contractInfoMapping", "partnerAccount");
                            } else {
                                trsDSP = "";
                            }
                        } else {
                            trsDSP = p_reqBat.readedDetail.askNumber;
                        }

                        tmpXElement.addChild(new XElement("TRSDSP", trsDSP));
                        nodeAnalysis(p_reqBat.readedDetail.srcXElement, tmpXElement, getCharset());
                        xmlWriter.writeXElement(tmpXElement);
                    }
                    xmlWriter.writeEndDocument();//写入报文完成
                } catch (Exception ex) {
                    isCompletePack = false;
                    FGBiz.limitMsg.exception(this.reqHeader.bankCode, ex);
                    sbLogChk.append(LogHelper.getStackTraceFirstLine(ex));
                }
            }

            //有明细写数据库操作，需要再次校验超时时间
            if (isCompletePack && checkBankPayOverTime(p_reqBat.getPayDateTime(), "5", sbLogChk)) {
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    //解析银行返回
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                        if (!StringHelper.isNullOrEmpty(tmpRetCode) && !tmpRetCode.equals("-9")) {
                            retAts.respCode = "0";
                            String tmpRSV50Z = tmpBkReader.getFirstText("/CMBSDKPGK/NTREQNBRY/RSV50Z");
                            if (tmpRSV50Z != null && tmpRSV50Z.length() > 0) {
                                retAts.transState = tmpRetCode + "+" + tmpRSV50Z;
                                retAts.payInfoCode = tmpRSV50Z;
                            } else {
                                retAts.transState = tmpRetCode;
                                retAts.payInfoCode = tmpRetCode;
                            }
                            retAts.respInfo = tmpRetMsg;
                            retAts.reqSeqID = p_reqBat.reqBatchNO;//tmpBkReader.getFirstText("/CMBSDKPGK/NTREQNBRY/REQNBR");
                            if (StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
                                retAts.reqSeqID = p_reqBat.reqBatchNO;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRetMsg;
                        }
                        if (tmpStrRet[1].contains("通讯故障") || tmpStrRet[1].contains("FBCM176")) {//FBCM176 通讯故障
                            retAts.respCode = "-1";
                            retAts.transState = "Unknow";
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else if (tmpStrRet[0].equals(ConnState.FAIL) || tmpStrRet[0].equals(FailCode.E9981)) {
                    retAts.respCode = "0";
                    retAts.respInfo = tmpStrRet[1];
                    retAts.reqSeqID = p_reqBat.reqBatchNO;
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = tmpStrRet[0];
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpStrRet[1];
                }
            } else {
                retAts.respCode = "0";
                retAts.respInfo = sbLogChk.toString();
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9999;
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            FGBiz.limitMsg.exception(reqHeader.bankCode + "." + reqHeader.transType, e);
        } finally {
            if (askAmtHelper != null) {
                askAmtHelper.close();
            }
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    //使用招行大批量代发经办接口，支持一次3000笔交易量
    public RetAtsBatPayRec d_BatPayRec_New(ReqBatPayRec p_reqBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        try {
            //N03020:代发
            String tmpBUSCOD = "N03020";
            String tmpBUSMOD = getBankConfig().getMapValueByKey("busmod" + tmpBUSCOD, p_reqBat.useType);
            String tmpC_TRSTYP = getBankConfig().getMapValueByKey("ctrstyp" + tmpBUSCOD, p_reqBat.useType);
            String tmp_TRSTYP = getBankConfig().getMapValueByKey("trstyp" + tmpBUSCOD, p_reqBat.useType);

            boolean isChecked = true;
            String tmpCheckMsg = "";
            if (StringHelper.isNullOrEmpty(tmpBUSMOD)) {
                isChecked = false;
                tmpCheckMsg = "未取到" + tmpBUSCOD + "的业务模式设置";
            }
            if (StringHelper.isNullOrEmpty(tmpBUSMOD)) {
                isChecked = false;
                if (tmpCheckMsg.length() > 0) {
                    tmpCheckMsg = tmpCheckMsg + "；";
                }
                tmpCheckMsg = tmpCheckMsg + "未取到" + tmpBUSCOD + "的交易代码名称设置";
            }
            if (!isChecked) {
                retAts.respCode = "0";
                retAts.respInfo = tmpCheckMsg;
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = "E9981";
                retAts.writeRetToATS();
                return retAts;
            }

            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTAGCAPY";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, tmpBnkHeader);

            boolean isCompletePack = true;
            StringBuilder sbLogChk = new StringBuilder();
            xmlWriter.writeStartElement("NTBUSMODY");
            xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);//业务模式
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("NTAGCAGCX1");
            xmlWriter.writeElementString("BEGTAG", "Y");        //批次开始标志
            xmlWriter.writeElementString("ENDTAG", "Y");        //批次结束标志
            xmlWriter.writeElementString("REQNBR", "");         //流程实例号
            xmlWriter.writeElementString("TTLAMT", p_reqBat.totalAmt);  //总金额
            xmlWriter.writeElementString("TTLCNT", p_reqBat.totalNum);  //总笔数
            xmlWriter.writeElementString("TTLNUM", "1");        //总次数
            xmlWriter.writeElementString("CURAMT", p_reqBat.totalAmt);  //本次金额
            xmlWriter.writeElementString("CURCNT", p_reqBat.totalNum);  //本次笔数
            xmlWriter.writeElementString("CNVNBR", "");         //合作方协议号
            xmlWriter.writeElementString("CCYNBR",
                    this.convertCurToBank(p_reqBat.ownCur));                         //交易货币
            xmlWriter.writeElementString("NTFINF", "");         //个性化短信内容
            xmlWriter.writeElementString("ACCNBR", p_reqBat.ownAct);     //帐号
            xmlWriter.writeElementString("BBKNBR", p_reqBat.ownArea);   //分行号
            xmlWriter.writeElementString("CCYMKT", "0");        //货币市场
            xmlWriter.writeElementString("TRSTYP", tmp_TRSTYP);         //交易类型
            xmlWriter.writeElementString("NUSAGE",
                    getBankConfig()
                            .getMapValueByKey("nusage", p_reqBat.useType));//用途
            xmlWriter.writeElementString("YURREF", p_reqBat.reqBatchNO);//对方参考号(取的是批次号)
            xmlWriter.writeEndElement();
            Map<String, String> map = new HashMap<String, String>();
            int count = 0;
            List<String> mappingList = new ArrayList<String>();
            try {
                //需要进行对账码拼接以及节点解析，采用XElement进行处理
                while (p_reqBat.readRecord()) {
                    count++;
                    String trxseq = String.format("%08d", count);
                    mappingList.add(trxseq);
                    XElement tmpXElement = new XElement("NTAGCDTLY1", "");
                    tmpXElement.addChild(new XElement("TRXSEQ", trxseq));  //交易序号
                    tmpXElement.addChild(new XElement("ACCNBR", p_reqBat.readedDetail.recAct));     //帐号
                    tmpXElement.addChild(new XElement("ACCNAM", p_reqBat.readedDetail.recName));    //户名
                    tmpXElement.addChild(new XElement("TRSAMT", p_reqBat.readedDetail.payAmount));  //金额
                    tmpXElement.addChild(new XElement("TRSDSP", p_reqBat.readedDetail.askNumber));  //注释
                    map.put(trxseq, p_reqBat.readedDetail.askNumber);
                    if (p_reqBat.readedDetail.sameBnk.equals("1")) {
                        tmpXElement.addChild(new XElement("BNKFLG", "Y"));
                        tmpXElement.addChild(new XElement("EACBNK", ""));
                        tmpXElement.addChild(new XElement("EACCTY", ""));
                    } else {
                        tmpXElement.addChild(new XElement("BNKFLG", "N"));
                        tmpXElement.addChild(new XElement("EACBNK", p_reqBat.readedDetail.getOppBankLocation()));
                        tmpXElement.addChild(new XElement("EACCTY", p_reqBat.readedDetail.getOppStandardArea()));
                    }
                    nodeAnalysis(p_reqBat.readedDetail.srcXElement, tmpXElement, getCharset());
                    xmlWriter.writeXElement(tmpXElement);
                }
                xmlWriter.writeEndDocument();//写入报文完成
            } catch (Exception ex) {
                isCompletePack = false;
                FGBiz.limitMsg.exception(this.reqHeader.bankCode, ex);
                sbLogChk.append(LogHelper.getStackTraceFirstLine(ex));
            }

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    //解析银行返回
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                        if (!StringHelper.isNullOrEmpty(tmpRetCode) && tmpRetCode.equals("0")) {
                            String REQNBR = tmpBkReader.getFirstText("/CMBSDKPGK/NTAGCAGCZ1/REQNBR");
                            Connection conn = FGBiz.getLocalDbConn();
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            //建立批次流水号和交易成功返回的交易序号(REQNBR)
                            JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_reqBat.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_reqBat.reqBatchNO, REQNBR});
                            //建立单笔交易和批次号和单笔流水的关系
                            if (map.size() > 0) {
                                Set<String> keySet = map.keySet();
                                for (String s : keySet) {
                                    //建立批次流水号+银行单笔号和交易成功返回的交易序号(TRXSEQ)
                                    uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                    JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_reqBat.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_reqBat.reqBatchNO + s, map.get(s)});
                                }
                            }

                            retAts.respCode = "0";
                            retAts.transState = tmpRetCode;
                            retAts.payInfoCode = tmpRetCode;
                            retAts.respInfo = tmpRetMsg;
                            retAts.reqSeqID = p_reqBat.reqBatchNO;//tmpBkReader.getFirstText("/CMBSDKPGK/NTREQNBRY/REQNBR");
                            if (StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
                                retAts.reqSeqID = p_reqBat.reqBatchNO;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRetMsg;
                        }
                        if (tmpStrRet[1].contains("通讯故障") || tmpStrRet[1].contains("FBCM176")) {//FBCM176 通讯故障
                            retAts.respCode = "-1";
                            retAts.transState = "Unknow";
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else if (tmpStrRet[0].equals(ConnState.FAIL) || tmpStrRet[0].equals(FailCode.E9981)) {
                    retAts.respCode = "0";
                    retAts.respInfo = tmpStrRet[1];
                    retAts.reqSeqID = p_reqBat.reqBatchNO;
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = tmpStrRet[0];
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpStrRet[1];
                }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            FGBiz.limitMsg.exception(reqHeader.bankCode + "." + reqHeader.transType, e);
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代付状态查询
     * @param p_req1998 批量代付查询请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        if ("198802".equals(p_req1998.reqHeader.commandCode) || "198801".equals(p_req1998.reqHeader.commandCode)) {
            return d_QryBatPayRec(p_req1998);
        } else if ("198803".equals(p_req1998.reqHeader.commandCode)){
            return d_QBatPayRec_New(p_req1998);
        } else {
            return null;
        }
    }

    private RetAtsQryBatPayRec checkPayStatus(ReqQryBatPayRec p_reqQryBat, boolean isFinished, StringBuilder tmpStrBatchREQSTA) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        CMB01Header tmpBnkHeader = new CMB01Header();
        tmpBnkHeader.FUNNAM = "NTAGCINN";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点

        xmlWriter.writeStartElement("NTAGCINNY1");
        xmlWriter.writeElementString("BUSCOD", "N03020");
        String tmpBUSMOD = getBankConfig().getMapValueByKey("busmod" + "N03020", "*");
        xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);
        Calendar tmpBGNDAT = Calendar.getInstance();
        tmpBGNDAT.setTime(p_reqQryBat.getBgnDateTime());
        tmpBGNDAT.add(Calendar.DAY_OF_MONTH, -1);

        Calendar tmpENDDAT = Calendar.getInstance();
        tmpENDDAT.setTime(p_reqQryBat.getBgnDateTime());
        tmpENDDAT.add(Calendar.DAY_OF_MONTH, 1);

        xmlWriter.writeElementString("BGNDAT", Format.Date8Format.format(tmpBGNDAT.getTime()));
        xmlWriter.writeElementString("ENDDAT", Format.Date8Format.format(tmpENDDAT.getTime()));
        xmlWriter.writeElementString("DATFLG", "A");

        xmlWriter.writeEndDocument();
        String tmpREQNBR = "";
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRetCode != null && "0".equals(tmpRetCode)) {
                        int tmpCountQYZ = tmpBkReader.countElement("/CMBSDKPGK/NTAGCINQZ");
                        if (tmpCountQYZ > 0) {
                            boolean isMatchYURREF = false;//是否有查询的批次
                            tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                            while (tmpBkReader.read("/CMBSDKPGK/NTAGCINQZ")) {
                                String tmpStrYURREF = tmpBkReader.readedXElement.getSingleText("YURREF");
                                if (tmpStrYURREF != null && p_reqQryBat.reqBatchNO.equals(tmpStrYURREF)) {
                                    isMatchYURREF = true;
                                    String tmpStrC_REQSTA = tmpBkReader.readedXElement.getSingleText("C_REQSTA");
                                    String tmpStrREQSTA = tmpBkReader.readedXElement.getSingleText("REQSTA");//业务请求状态
                                    String tmpStrRTNFLG = tmpBkReader.readedXElement.getSingleText("RTNFLG");
                                    String tmpStrSUCAMT = tmpBkReader.readedXElement.getSingleText("SUCAMT");
                                    String tmpStrSUCNUM = tmpBkReader.readedXElement.getSingleText("SUCNUM");
                                    String tmpStrERRDSP = tmpBkReader.readedXElement.getSingleText("ERRDSP");

                                    tmpStrBatchREQSTA.append(tmpStrREQSTA);
                                    retAts.reqSeqID = tmpStrYURREF;

                                    if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                        tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                    }
                                    if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F")) {
                                        float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                        float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                        if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                            retAts.respCode = "0";
                                            retAts.respInfo = tmpStrERRDSP;
                                            retAts.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                            retAts.payInfoCode = tmpStrERRDSP;
                                            isFinished = true;
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "成功笔数或成功金额不符合预期";
                                        }
                                    } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                        retAts.respCode = "0";
                                        retAts.respInfo = tmpStrC_REQSTA;
                                        retAts.transState = tmpStrREQSTA;
                                        retAts.payInfoCode = tmpStrREQSTA;
                                        isFinished = true;
                                    } else if (StringHelper.isNullOrEmpty(tmpStrREQSTA)) {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "批次的业务请求状态为空";
                                    }
                                    break;
                                }
                            }

                            if (!isFinished && !isMatchYURREF && !tmpStrRet[1].contains(p_reqQryBat.reqBatchNO)) {
                                if (canBeNotExist(p_reqQryBat, retAts, 45)) {
                                    retAts.respCode = "0";
                                    retAts.respInfo = "招行不存在该批次号";
                                    retAts.transState = PaymentState.FAIL_Batch;
                                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                    retAts.payInfoCode = "E1302";
                                    isFinished = true;
                                }
                            }
                        } else if (tmpCountQYZ == 0) {
                            tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                            boolean tmpReadRoot = tmpBkReader.read("/CMBSDKPGK");
                            int tmpCountChild = -1;
                            if (tmpReadRoot) {
                                tmpCountChild = tmpBkReader.readedXElement.countChildren();
                            }
                            if (tmpRetCode.equals("0") && tmpStrRet[1].indexOf("NTAGCINQZ") < 0 && tmpReadRoot && tmpCountChild == 1 && !tmpStrRet[1].contains(p_reqQryBat.reqBatchNO)) {
                                if (canBeNotExist(p_reqQryBat, retAts, 45)) {
                                    retAts.respCode = "0";
                                    retAts.respInfo = "招行不存在该业务参考号";
                                    retAts.transState = PaymentState.FAIL_Batch;
                                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                    retAts.payInfoCode = "E1302";
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "招行返回报文不符合预期";
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "招行返回的批次" + "NTAGCINQZ" + "节点不符合预期";
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetMsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        return retAts;
    }


    private RetAtsQryBatPayRec d_QBatPayRec_New(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        boolean isFinished = false;
        StringBuilder sb = new StringBuilder();
        RetAtsQryBatPayRec retAtsCheck = checkPayStatus(p_req1998, isFinished, sb);

        if (isFinished || "-1".equals(retAtsCheck.respCode)) {
            retAtsCheck.writeAfterDetail();
            return retAtsCheck;
        }

        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTAGDINF";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点

            //从SQLlite中取对账码
            Connection conn = FGBiz.getLocalDbConn();
            Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1998.reqBatchNO});
            String reqnbr = null;
            if (selMap != null & selMap.size() > 0) {
                reqnbr = selMap.get("BANKREQSEQID").toString();
            } else {
                retAts.writeBatRespCode("-1");
                retAts.writeBatRespInfo("无该批次交易信息,需要联系技术人员排查原因");
            }
            xmlWriter.writeStartElement("NTAGDINFY1");
            xmlWriter.writeElementString("REQNBR", reqnbr);
            xmlWriter.writeEndElement();
            xmlWriter.writeEndElement();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode) && "0".equals(tmpRetCode)) {
                        retAts.respCode = "0";
                        retAts.writeBeforeDetail();
                        while (tmpBkReader.read("/CMBSDKPGK/NTAGCDTLY1")) {
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("ACCNBR");
                            tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("ACCNAM");
                            tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("TRSAMT");
                            tmpRetDetail.result = sb.toString() + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            Map<String, Object> postScriptMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1998.reqBatchNO + tmpBkReader.readedXElement.getSingleText("TRXSEQ")});
                            if (postScriptMap != null && postScriptMap.size() > 0) {
                                tmpRetDetail.postScript = postScriptMap.get("BANKREQSEQID").toString();
                            } else {
                                retAts.writeBatRespCode("-1");
                                retAts.writeBatRespInfo("无该交易信息记录，需要联系技术人员排查原因，该批次号为：" + p_req1998.reqBatchNO + "，批次内交易序号为：" + tmpBkReader.readedXElement.getSingleText("TRXSEQ"));
                            }
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        retAts.writeBeforeDetail();
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetMsg;
                    }
                } else {
                    retAts.writeBeforeDetail();
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.writeBeforeDetail();
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            FGBiz.limitMsg.exception(reqHeader.bankCode + "." + reqHeader.transType, e);
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    /**
     * 批量代扣
     * @param p_req9198 批量代扣查询请求对象
     * @return
     * @throws Exception
     */
    //9198
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    /**
     * 从缓存文件取批次信息，因为是按日缓存，缓存没有不代表没这批次数据！！！
     */
    private HashMap<String, String> getBkBatFromCacheFile(String pCacheFile, String pReqBatchNO, RetAtsQryBatPayRec retAts) {
        HashMap<String, String> retMap = new HashMap<String, String>();
        try {
            if (FileHelper.existFile(pCacheFile)) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(FileHelper.readFileText(pCacheFile, "utf-8"), tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        String tmpNodeRet = "NTAGCINQZ";
                        int tmpCountQYZ = tmpBkReader.countElement("/CMBSDKPGK/" + tmpNodeRet);
                        //如果useNewBatQuery，是按天查询的，查回所有批次后，再提取
                        if (tmpCountQYZ > 0) {
                            tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                            while (tmpBkReader.read("/CMBSDKPGK/" + tmpNodeRet)) {
                                String tmpStrYURREF = tmpBkReader.readedXElement.getSingleText("YURREF");
                                if (tmpStrYURREF != null && pReqBatchNO.equals(tmpStrYURREF)) {
                                    retMap.put("matched", "true");

                                    String isFinished = "false";
                                    String tmpStrC_REQSTA = tmpBkReader.readedXElement.getSingleText("C_REQSTA");
                                    String tmpStrREQSTA = tmpBkReader.readedXElement.getSingleText("REQSTA");//业务请求状态
                                    String tmpStrRTNFLG = tmpBkReader.readedXElement.getSingleText("RTNFLG");
                                    String tmpStrSUCAMT = tmpBkReader.readedXElement.getSingleText("SUCAMT");
                                    String tmpStrSUCNUM = tmpBkReader.readedXElement.getSingleText("SUCNUM");
                                    String tmpStrERRDSP = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                                    String tmpREQNBR = tmpBkReader.readedXElement.getSingleText("REQNBR");
                                    retMap.put("REQNBR", tmpREQNBR);
                                    retMap.put("StrBatchREQSTA", tmpStrREQSTA);
                                    retMap.put("StrBatchRTNFLG", tmpStrRTNFLG);
                                    retAts.reqSeqID = tmpStrYURREF;
                                    if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                        tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                    }
                                    if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F") && StringHelper.isNullOrEmpty(tmpREQNBR)) {
                                        float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                        float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                        if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                            retAts.respCode = "0";
                                            retAts.respInfo = tmpStrERRDSP;
                                            retAts.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                            retAts.payInfoCode = tmpStrERRDSP;
                                            isFinished = "true";
                                        }
                                    } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                        retAts.respCode = "0";
                                        retAts.respInfo = tmpStrC_REQSTA;
                                        retAts.transState = tmpStrREQSTA;
                                        retAts.payInfoCode = tmpStrREQSTA;
                                        isFinished = "true";
                                    }
                                    retMap.put("isFinished", isFinished);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            FGBiz.limitMsg.exception(this.reqHeader.bankCode, e);
            this.WriteBankLogLn(LogHelper.getStackTrace(e));
        }
        return retMap;
    }

    //批量代收和批量代付状态查询
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        //N03010:代发工资   N03020:代发   N03030:代扣
        //198802 代发工资
        String tmpBUSCOD = "";
        if (p_reqQryBat.reqHeader.transType.equals("1998")) {
            if (p_reqQryBat.reqHeader.commandCode.equals("198802")) {
                tmpBUSCOD = "N03010";
            } else {
                tmpBUSCOD = "N03020";
            }
        } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
            tmpBUSCOD = "N03030";
        }

        CMB01Header tmpBnkHeader = new CMB01Header();

        boolean useNewBatQuery = getBankConfig().getValueAsBool("useNewBatQuery");

        tmpBnkHeader.FUNNAM = "GetAgentInfo";
        if (useNewBatQuery) {
            tmpBnkHeader.FUNNAM = "NTAGCINN";
        }
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        if (useNewBatQuery) {
            xmlWriter.writeStartElement("NTAGCINNY1");
        } else {
            xmlWriter.writeStartElement("SDKATSQYX");
        }

        xmlWriter.writeElementString("BUSCOD", tmpBUSCOD);
        String tmpBUSMOD = getBankConfig().getMapValueByKey("busmod" + tmpBUSCOD, "*");
        xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);
        Calendar tmpBGNDAT = Calendar.getInstance();
        tmpBGNDAT.setTime(p_reqQryBat.getBgnDateTime());
        tmpBGNDAT.add(Calendar.DAY_OF_MONTH, -1);

        Calendar tmpENDDAT = Calendar.getInstance();
        tmpENDDAT.setTime(p_reqQryBat.getBgnDateTime());
        tmpENDDAT.add(Calendar.DAY_OF_MONTH, 1);

        xmlWriter.writeElementString("BGNDAT", Format.Date8Format.format(tmpBGNDAT.getTime()));
        xmlWriter.writeElementString("ENDDAT", Format.Date8Format.format(tmpENDDAT.getTime()));

        xmlWriter.writeElementString("DATFLG", "A");

        if (!useNewBatQuery) {
            xmlWriter.writeElementString("YURREF", p_reqQryBat.reqBatchNO);
            xmlWriter.writeElementClosed("OPRLGN");
        }

        xmlWriter.writeEndDocument();
        boolean isFinished = false;
        String tmpREQNBR = "";
        String tmpStrBatchREQSTA = "";
        String tmpStrBatchRTNFLG = "";
        try {

            String resultCacheFile = Format.Date8Format.format(p_reqQryBat.getBgnDateTime()) + "_" + this.bankFront.code + "_" + tmpBnkHeader.FUNNAM + "_" + tmpBUSCOD + "_" + tmpBUSMOD + ".txt";
            String saveTo = this.getTempFileDirectory(p_reqQryBat.getBgnDateTime()) + File.separator + resultCacheFile;

            boolean isHitCache = false;
            if (useNewBatQuery) {
                WriteBankLogLn("批次缓存文件" + saveTo);
                HashMap<String, String> cacheBat = getBkBatFromCacheFile(saveTo, p_reqQryBat.reqBatchNO, retAts);
                if (cacheBat.containsKey("matched") && "true".equals(cacheBat.get("matched"))) {
                    this.WriteBankLogLn("从缓存文件中匹配到该批次数据，直接取缓存");
                    if ("true".equals(cacheBat.get("isFinished"))) {
                        isFinished = true;
                    }
                    tmpREQNBR = cacheBat.get("REQNBR");
                    tmpStrBatchREQSTA = cacheBat.get("StrBatchREQSTA");
                    tmpStrBatchRTNFLG = cacheBat.get("StrBatchRTNFLG");
                    isHitCache = true;
                    if ("BNK".equalsIgnoreCase(tmpStrBatchREQSTA) || "BNK".equalsIgnoreCase(retAts.transState)) {
                        isFinished = false;
                        isHitCache = false;
                    }
                }
            }
            if (!isHitCache) {
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                        if (tmpRetCode != null && tmpRetCode.equals("0")) {
                            String tmpNodeRet = "NTQATSQYZ";
                            if (useNewBatQuery) {
                                tmpNodeRet = "NTAGCINQZ";
                            }

                            int tmpCountQYZ = tmpBkReader.countElement("/CMBSDKPGK/" + tmpNodeRet);
                            //如果useNewBatQuery，是按天查询的，查回所有批次后，再提取
                            if (useNewBatQuery && tmpCountQYZ > 0) {

                                //按日查询，缓存一下数据，招行对查询有限制
                                //已经查回的，不需要再次查询，加快速度

                                FileHelper.deleteFileIfExists(saveTo);
                                FileHelper.writeFile(saveTo, tmpStrRet[1], "utf-8");
                                WriteBankLogLn("已保存缓存文件" + saveTo);

                                boolean isMatchYURREF = false;//是否有查询的批次
                                tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                                while (tmpBkReader.read("/CMBSDKPGK/" + tmpNodeRet)) {
                                    String tmpStrYURREF = tmpBkReader.readedXElement.getSingleText("YURREF");
                                    if (tmpStrYURREF != null && p_reqQryBat.reqBatchNO.equals(tmpStrYURREF)) {
                                        isMatchYURREF = true;
                                        String tmpStrC_REQSTA = tmpBkReader.readedXElement.getSingleText("C_REQSTA");
                                        String tmpStrREQSTA = tmpBkReader.readedXElement.getSingleText("REQSTA");//业务请求状态
                                        String tmpStrRTNFLG = tmpBkReader.readedXElement.getSingleText("RTNFLG");
                                        String tmpStrSUCAMT = tmpBkReader.readedXElement.getSingleText("SUCAMT");
                                        String tmpStrSUCNUM = tmpBkReader.readedXElement.getSingleText("SUCNUM");
                                        String tmpStrERRDSP = tmpBkReader.readedXElement.getSingleText("ERRDSP");

                                        tmpREQNBR = tmpBkReader.readedXElement.getSingleText("REQNBR");
                                        tmpStrBatchREQSTA = tmpStrREQSTA;
                                        tmpStrBatchRTNFLG = tmpStrRTNFLG;
                                        retAts.reqSeqID = tmpStrYURREF;

                                        if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                            tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                        }
                                        if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F")) {
                                            float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                            float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                            if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                                retAts.respCode = "0";
                                                retAts.respInfo = tmpStrERRDSP;
                                                retAts.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                                retAts.payInfoCode = tmpStrERRDSP;
                                                isFinished = true;
                                            } else {
                                                retAts.respCode = "-1";
                                                retAts.respInfo = "成功笔数或成功金额不符合预期";
                                            }
                                        } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                            retAts.respCode = "0";
                                            retAts.respInfo = tmpStrC_REQSTA;
                                            retAts.transState = tmpStrREQSTA;
                                            retAts.payInfoCode = tmpStrREQSTA;
                                            isFinished = true;
                                        } else if (StringHelper.isNullOrEmpty(tmpStrREQSTA)) {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "批次的业务请求状态为空";
                                        }
                                        break;
                                    }
                                }

                                if (!isFinished && !isMatchYURREF && !tmpStrRet[1].contains(p_reqQryBat.reqBatchNO)) {
                                    if (canBeNotExist(p_reqQryBat, retAts, 45)) {
                                        retAts.respCode = "0";
                                        retAts.respInfo = "招行不存在该批次号";
                                        retAts.transState = PaymentState.FAIL_Batch;
                                        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                        retAts.payInfoCode = "E1302";
                                        isFinished = true;
                                    }
                                }
                            } else if (!useNewBatQuery && tmpCountQYZ > 0) {
                                String tmpStrC_REQSTA = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/C_REQSTA");
                                String tmpStrREQSTA = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/REQSTA");//业务请求状态
                                //业务处理结果//当REQSTA=FIN且RTNFLG=S需检查RSV62Z第一位是否为’P’，是表示部分成功，否则表示全部成功。
                                String tmpStrRTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/RTNFLG");
                                String tmpStrSUCAMT = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/SUCAMT");
                                String tmpStrSUCNUM = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/SUCNUM");
                                String tmpStrERRDSP = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/ERRDSP");
                                String tmpStrYURREF = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/YURREF");

                                tmpREQNBR = tmpBkReader.getFirstText("/CMBSDKPGK/" + tmpNodeRet + "/REQNBR");
                                if (tmpStrYURREF != null && p_reqQryBat.reqBatchNO.equals(tmpStrYURREF)) {
                                    tmpStrBatchREQSTA = tmpStrREQSTA;
                                    tmpStrBatchRTNFLG = tmpStrRTNFLG;
                                    retAts.reqSeqID = tmpStrYURREF;
                                    if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                        tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                    }
                                    if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F") && StringHelper.isNullOrEmpty(tmpREQNBR)) {
                                        float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                        float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                        if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                            retAts.respCode = "0";
                                            retAts.respInfo = tmpStrERRDSP;
                                            retAts.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                            retAts.payInfoCode = tmpStrERRDSP;
                                            isFinished = true;
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "成功笔数或成功金额不符合预期";
                                        }
                                    } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                        retAts.respCode = "0";
                                        retAts.respInfo = tmpStrC_REQSTA;
                                        retAts.transState = tmpStrREQSTA;
                                        retAts.payInfoCode = tmpStrREQSTA;
                                        isFinished = true;
                                    } else if (StringHelper.isNullOrEmpty(tmpStrREQSTA)) {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "批次的业务请求状态为空";
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "招行批号" + tmpStrYURREF + "与请求批号" + p_reqQryBat.reqBatchNO + "不相符";
                                }
                            } else if (tmpCountQYZ == 0) {
                                tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                                boolean tmpReadRoot = tmpBkReader.read("/CMBSDKPGK");
                                int tmpCountChild = -1;
                                if (tmpReadRoot) {
                                    tmpCountChild = tmpBkReader.readedXElement.countChildren();
                                }
                                if (tmpRetCode.equals("0") && tmpStrRet[1].indexOf(tmpNodeRet) < 0 && tmpReadRoot && tmpCountChild == 1 && !tmpStrRet[1].contains(p_reqQryBat.reqBatchNO)) {
                                    if (canBeNotExist(p_reqQryBat, retAts, 45)) {
                                        retAts.respCode = "0";
                                        retAts.respInfo = "招行不存在该业务参考号";
                                        retAts.transState = PaymentState.FAIL_Batch;
                                        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                        retAts.payInfoCode = "E1302";
                                        isFinished = true;
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "招行返回报文不符合预期";
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "招行返回的批次" + tmpNodeRet + "节点不符合预期";
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRetMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpStrRet[1];
                }
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }

        if (isFinished || "-1".equals(retAts.respCode)) {
            retAts.writeAfterDetail();
            return retAts;
        }

        //查明细
        if ("918802".equals(p_reqQryBat.reqHeader.commandCode)) {
            tmpBnkHeader.FUNNAM = "NTAGDINF";
        } else {
            tmpBnkHeader.FUNNAM = "GetAgentDetail";
        }
        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        if ("918802".equals(p_reqQryBat.reqHeader.commandCode)) {
            xmlWriter.writeStartElement("NTAGDINFY1");//
            xmlWriter.writeElementString("REQNBR", tmpREQNBR);
        } else {
            xmlWriter.writeStartElement("SDKATDQYX");//
            xmlWriter.writeElementString("REQNBR", tmpREQNBR);
        }

        xmlWriter.writeEndDocument();
        AskNumAmtHelper askNumHelper = null;
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        retAts.respCode = "0";
                        retAts.writeBeforeDetail();

                        boolean noAsk = false;//流水号不能在查询带回

                        if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                            String userPartnerAccount = getBankConfig().getValueAsString("isUserPartnerAccount");
                            if (StringHelper.hasAnyChar(userPartnerAccount)) {
                                noAsk = true;
                                askNumHelper = new AskNumAmtHelper(p_reqQryBat.reqHeader.tenant, p_reqQryBat.getBgnDateTime());
                                askNumHelper.initMatch(p_reqQryBat.reqBatchNO);
                            }
                        }
                        int rdCounting = 0;
                        int matchedCount = 0;
                        tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                        while (tmpBkReader.read("/CMBSDKPGK/NTQATDQYZ")) {
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            if (p_reqQryBat.reqHeader.transType.equals("1998")) {
                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("ACCNBR");
                                tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("CLTNAM");
                            } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
                                tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("ACCNBR");
                                tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("CLTNAM");
                            }
                            tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("TRSAMT");
                            tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("TRSDSP");
                            tmpRetDetail.result = tmpStrBatchREQSTA + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            boolean isFinalState = true;//是否是终态
                            if ("F".equals(tmpStrBatchRTNFLG) && "I".equals(tmpBkReader.readedXElement.getSingleText("STSCOD"))) {
                                tmpRetDetail.result = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            } else if (!"FIN".equals(tmpStrBatchREQSTA) && "I".equals(tmpBkReader.readedXElement.getSingleText("STSCOD"))) {
                                isFinalState = false;//非终态，即处理中
                            }
                            tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            if (tmpRetDetail.payInfoCode != null && tmpRetDetail.payInfoCode.length() > 32) {
                                tmpRetDetail.payInfoCode = tmpRetDetail.payInfoCode.substring(0, 33);
                            }
                            rdCounting++;
                            if (noAsk) {//招行不支持返回流水号，需根据金额户名账号进行匹配
                                if (askNumHelper.matchAskNum(p_reqQryBat.reqHeader.transType, tmpRetDetail, rdCounting, isFinalState)) {
                                    matchedCount++;
                                } else {
                                    break;
                                }
                            }
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                        tmpBkReader.resetReadMode(XmlReadMode.XElementReader);
                        while (tmpBkReader.read("/CMBSDKPGK/NTAGCDTLY1")) {
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            if (p_reqQryBat.reqHeader.transType.equals("9198")) {
                                tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("ACCNBR");
                                tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("ACCNAM");
                            }
                            tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("TRSAMT");
                            tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("TRXSEQ");
                            tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("TRSDSP");
                            tmpRetDetail.result = tmpStrBatchREQSTA + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            boolean isFinalState = true;//是否是终态
                            if ("F".equals(tmpStrBatchRTNFLG) && "I".equals(tmpBkReader.readedXElement.getSingleText("STSCOD"))) {
                                tmpRetDetail.result = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            } else if (!"FIN".equals(tmpStrBatchREQSTA) && "I".equals(tmpBkReader.readedXElement.getSingleText("STSCOD"))) {
                                isFinalState = false;//非终态，即处理中
                            }
                            tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            if (tmpRetDetail.payInfoCode != null && tmpRetDetail.payInfoCode.length() > 32) {
                                tmpRetDetail.payInfoCode = tmpRetDetail.payInfoCode.substring(0, 33);
                            }
                            rdCounting++;
                            if (noAsk) {//招行不支持返回流水号，需根据金额户名账号进行匹配
                                if (askNumHelper.matchAskNum(p_reqQryBat.reqHeader.transType, tmpRetDetail, rdCounting, isFinalState)) {
                                    matchedCount++;
                                } else {
                                    break;
                                }
                            }
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                        if (noAsk) {
                            HelperResp resp = askNumHelper.checkMatchCount(rdCounting, matchedCount);
                            if (!resp.isCompleted) {//总笔数校验不通过
                                retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
                                retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                retAts.respCode = "-1";
                                retAts.respInfo = resp.sbMsg.toString();
                            }
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetMsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            FGBiz.limitMsg.exception(this.getLogCode(), e);
            retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
        } finally {
            if (askNumHelper != null) {
                askNumHelper.close();
            }
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
